<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends CI_Controller {
	function __construct(){
		parent:: __construct();
		$this->load->model("mod_book");
		$this->load->model("mod_user");
		$this->load->library('form_validation');
		$this->load->library("pagination");
		$this->loggedIn();
	}
	protected function loggedIn(){
		if (!$this->session->userdata('admin_loggedIn'))
		  {
		  redirect('login');		  
		}
	}
	function index(){
		$this->load->view("index_admin");
	}
	function editBook($editUserId){
		$arr = explode("_", $editUserId);
		$id = $arr[1];
		$data['title'] = "Edit Books";
		$data['page'] = "editBook";
		$this->form_validation->set_rules("bookName","Book Title","trim|required");
		$this->form_validation->set_rules("price","Price","trim|required");
		$data['resultData'] = $this->mod_book->getDetailBook($id);
		$this->load->view("index_admin",$data);
	}
	function returnOrderBook($bookOrderId){
		$arr = explode("_", $bookOrderId);
		$id = $arr[1];
		$this->mod_user->returnOrderBook($id);
		redirect("admin/viewOrderBook");
	}
	function noreturnOrderBook($bookOrderId){
		$arr = explode("_", $bookOrderId);
		$id = $arr[1];
		$this->mod_user->noreturnOrderBook($id);
		redirect("admin/viewOrderBook");
	}
	function deleteOrderBook($bookOrderId){
		$this->mod_user->deleteOrderBook($bookOrderId);
		redirect("admin/viewOrderBook");
	}
	function updateBooks($editUserId){
		$name = $this->input->post("bookName");
		$lable = $this->input->post("label");
		$price = $this->input->post("price");
		$shipping = $this->input->post("shipping");
		$old = $this->input->post("img");
		$dec = $this->input->post("txtComDese");

		if($_FILES["userfile"]['name'] != ""){
                $config['upload_path'] = "./public/img/books/";
                $config['allowed_types'] = 'jpg|png|gif';
                $config['max_size'] = '7168'; //max size is 7MB
                $this->load->library('upload', $config);
            if($this->upload->do_upload()) {
						$file_info = $this->upload->data();
						$imgs = $file_info['file_name'];
				  
						$config['source_image'] =  $config['upload_path'].$imgs;
						$config['maintain_ratio'] = TRUE;
						$config['width']     = 535;
						$config['height']   = 647;
						$this->load->library('image_lib', $config); 
						$this->image_lib->resize();
						@unlink( $config['upload_path'].$old );

            }else{
            	 $this->session->set_flashdata("msg", "<div class='alert alert-danger'> Problem with uploading , check size and type</div>");
            	 redirect("admin/editBook/bookId_".$editUserId);
            }
		}else{
			$imgs = $old;
		}
		 $this->session->set_flashdata("msg", "<div class='alert alert-success'> You are successfully</div>");
		$this->mod_user->updateBook($editUserId,$name,$lable,$price,$dec,$imgs,$shipping);
		redirect("admin/viewBook");
	}

	function viewOrderBook($offest=NULL){
		$data['title'] = "All Books";
		$data['page'] = "viewOrderBook";
		$limit                   = 10;
        $segment                 = 3;
        $num_link                = 5;
       
        $total_rows              = $this->mod_user->count_table("tbl_order_detail");
        $base_url                = base_url()."index.php/admin/viewOrderBook";
        pagination($limit, $segment, $base_url, $total_rows, $num_link);
       	//$data['employee_data'] = $this->mod_khmerhr_admin->getUser($limit, $offest);
       	$data['result'] = $this->mod_user->viewOrderBook($limit, $offest);
       
        $data['links']           = $this->pagination->create_links();
		
		$this->load->view("index_admin",$data);
	}
	function getAllCountry(){
		$data['title'] = "Country";
		$data['page'] = "country";


		 $segment                 = 3;
        $num_link                = 5;
        $total_rows              = $this->mod_user->count_table("tbl_country");
        $base_url                = base_url()."index.php/admin/getAllCountry";
        pagination($limit, $segment, $base_url, $total_rows, $num_link);
       	
       $data['result'] = $this->mod_user->getAllCountry($limit, $offest);
        $data['links']           = $this->pagination->create_links();
        $data["totalLocation"] = $total_rows;
		
		


		
		$this->load->view("index_admin",$data);
	}

	function viewBook(){
		$data['title'] = "All Books";
		$data['page'] = "viewBook";
		$data['result'] = $this->mod_book->viewpost();
		$this->load->view("index_admin",$data);
	}
	function addBook(){
		
		$data['title'] = "Add Book";
		$data['page'] = "addBook";
		$data['errorImg'] = "";
		$this->form_validation->set_rules('bookName', 'Book Title', 'required');
	    $this->form_validation->set_rules('price', 'Price', 'required');
	    $this->form_validation->set_rules('shipping', 'Shipping', 'required');
		$this->form_validation->set_rules('label', 'Label', 'required');
		
		
		/*if($_FILES["userfile"]['name'] == ""){
			
		
		}*/
		if($this->form_validation->run() === false){
			
			$this->load->view("index_admin",$data);
		} else{	
		        $config['upload_path'] = "./public/img/books/";
				$config['allowed_types'] = 'jpg|png|gif';
				$config['max_size'] = '7168'; //max size is 7MB
				$this->load->library('upload', $config);
				
				$name = $this->input->post("bookName");
				$lable = $this->input->post("label");
				$detial = $this->input->post("txtComDese");
				$price = $this->input->post("price");
				$shipping = $this->input->post("shipping");
			
				if($this->upload->do_upload()) {
						$file_info = $this->upload->data();
						$imgs = $file_info['file_name'];
						$config['source_image'] =  $config['upload_path'].$imgs;
						$config['maintain_ratio'] = TRUE;
						$config['width']     = 535;
						$config['height']   = 647;
						$this->load->library('image_lib', $config); 
						$this->image_lib->resize();
						$this->mod_book->addBook($name,$lable,$detial,$price,$imgs,$shipping);
						
						redirect("admin/viewBook");

				}else{
					// $this->session->set_flashdata("msg", "<div class='alert alert-danger'> Problem with uploading , check size and type</div>");
					$data["errorImg"] = $this->upload->display_errors();
					$this->load->view("index_admin",$data);
				}
				
			
		}
		
	}
	function logout(){
		$this->session->sess_destroy();
		redirect('book');
	}

	// Thymeak

	function deletepost($postid){
		$data['title'] = "All Books";
		$data['page'] = "viewBook";
		$this->mod_book->deletepost($postid);
		redirect("admin/viewBook");
	}
	// Thymeak

	//Start Neth
	function viewUsers(){
		$data['title'] = "All Users";
		$data['page'] = "viewUsers";
		$data['result'] = $this->mod_user->users_list();
		$this->load->view("index_admin",$data);
	}	
	function addUser(){
		$data['title'] = "Add User";
		$data['page'] = "addUser";
		$data['errorImg'] = "";

		$data['country']=$this->mod_user->fetch_country();
		$data['userrole']=$this->mod_user->fetch_userrole();				

		$this->form_validation->set_rules('fName', 'First name', 'required');
		$this->form_validation->set_rules('lName', 'Last name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('phone', 'Phone', 'required');
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[conpassword]|md5');
		$this->form_validation->set_rules('conpassword', 'Confirm password', 'trim|required');
	  
		if($this->form_validation->run() === false){			
			$this->load->view("index_admin",$data);
		}else{			
				$fName = $this->input->post("fName");
				$lName = $this->input->post("lName");
				$email = $this->input->post("email");
				$phone = $this->input->post("phone");
				$username = $this->input->post("username");
				$password = $this->input->post("password");
				$roleid = $this->input->post("cborole");
				$countryid = $this->input->post("cbocountry");
				$gender = $this->input->post("cbogender");
				$status = $this->input->post("cbostatus");
				
				$this->mod_user->addUser($fName,$lName,$email,$phone,$username,$password,$roleid,$countryid,$gender,$status);				
				redirect("admin/viewUsers");
		}		
	}
	function editUser(){
		$data['title'] = "Edit Users";
		$data['page'] = "editUser";		
		$data['country']=$this->mod_user->fetch_country();
		$data['userrole']=$this->mod_user->fetch_userrole();
		if ( $this->uri->segment(3) != '' ) {
			$userid = $this->uri->segment(3);
			$this->session->set_userdata("adminuserid",$userid);			
		}else{		
			redirect("admin/viewUsers");
		}
		

		$this->form_validation->set_rules('fName', 'First name', 'required');
		$this->form_validation->set_rules('lName', 'Last name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('phone', 'Phone', 'required');
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[conpassword]|md5');
		$this->form_validation->set_rules('conpassword', 'Confirm password', 'trim|required');	

		if($this->form_validation->run() === false){			
			$this->load->view("index_admin",$data);
		}else{		

			$arr = array(
				'roleid'=>$this->input->post("cborole")
				,'firstname'=>$this->input->post("fName")
				,'lastname'=>$this->input->post("lName")
				,'fullname'=>$this->input->post("fName").' '.$this->input->post("lName")
				,'email'=>$this->input->post("email")
				,'countryid'=>$this->input->post("cbocountry")
				,'phone_num'=>$this->input->post("phone")
				,'username'=>$this->input->post("username")
				,'password'=>$this->input->post("password")
				,'isdeleted'=>0
				,'gender'=>$this->input->post("cbogender")
				,'status'=>$this->input->post("cbostatus")
				,'createdate'=>date('Y-m-d'),			
			);				

			$this->mod_user->editUser($arr,$this->session->userdata("adminuserid"));				
			redirect("admin/viewUsers");			
		}	
		
	}
	function deleteUser(){
		$data['title'] = "Delete User";
		$data['page'] = "deleteUser";
		//$data['result'] = $this->mod_user->users_list();

		$userID = $this->uri->segment(3); 
		$this->load->view("index_admin",$data);
	}
	function addRegister(){				   	

		$this->form_validation->set_rules('email', 'Email', 'trim|required');
		$this->form_validation->set_rules('agree', 'Check Book', 'required');
		$email = $this->input->post("email");
		$agree = $this->input->post("agree");	
		
		

		if($this->form_validation->run() === false){ 
			redirect("book/register");
		}else{ 
			$id = $this->mod_book->addRegisterEmail($email,$agree);
			$link =    '<a class="btn btn-danger" href="'.base_url().'index.php/book/validateEmail/'.$id.'">'.base_url().'index.php/book/validateEmail/'.$id.'</a>';   		

			$to      = $email;
			$subject = 'Thanks for join with us';			 
			$headers = 'From: editiondelaplushautetour.com';
			$message = 'Please click this link to verify your account '.$link;	

		 			  	        			        	   
	       if(mail($to, $subject, $message, $headers)){

	       		mail($to, $subject, $message, $headers);
				$this->session->set_userdata("usermail",$email);

	       }else{
	       		$this->mod_book->deleteuserbymail($email);
	       		$this->session->unset_userdata('usermail');       	
	        }
         			             
			redirect('book/register');
		}
       }
	//End Neth	
}